<template>
  <div>
    <data-table
      ref="roleTable"
      :value="tableData"
      :has-action="true"
      :table-column-attributes="tableColumnAttributes"
      :width="160"
      :isShowPage="true"
      :isShowSelection="true"
      :hasAction="false"
      :totalCount="totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @selection-change="selectionChange"
      @row-click="clickRow"
    ></data-table>
    <div style="text-align: center">
      <el-button type="primary" @click="selectOnClick">确定</el-button>
    </div>
  </div>
</template>
<script>
import baseMixin from "@/mixins/base";
import { userPage } from "@/api/after-sale/personnel/index";
export default {
  mixins: [
    baseMixin({
      idName: "id",
      findData: userPage,
      dataName: ["content", "totalRecords"],
    }),
  ],
  props: {
    checkList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    formData: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      //table字段
      tableColumnAttributes: [
        {
          name: "姓名",
          value: "userName",
          type: "text",
        },
        {
          name: "手机号",
          value: "phone",
          type: "text",
        },
        {
          name: "任职门店",
          value: "storeName",
          type: "text",
        },
      ],
      sleect: [],
    };
  },
  watch: {
    tableData: {
      handler(newVal, oldVal) {
        setTimeout(() => {
          //设置表格的选中状态 延时5毫秒等待表格渲染完成
          this.filterData(newVal).forEach((row) => {
            console.log(this.$refs.roleTable.$refs.multipleTable);
            this.$refs.roleTable.$refs.multipleTable.toggleRowSelection(row, true);
          });
        }, 300);
      },
      deep: true,
    },
  },
  methods: {
    //过滤选中的数据
    filterData(data) {
      return data.filter((item) => {
        for (let index = 0; index < this.checkList.length; index++) {
          if (item.id == this.checkList[index]) {
            return item;
          }
        }
      });
    },
    clickRow(row) {
      if (this.sleect.length == 1) {
        this.sleect = [];
        this.$refs.roleTable.$refs.multipleTable.clearSelection();
      } else {
        this.$refs.roleTable.$refs.multipleTable.toggleRowSelection(row, true);
      }
    },
    selectOnClick() {
      this.$emit("roleIdListSelectCheck", this.sleect);
    },
    selectionChange(sleect) {
      //TODO 待优化  这里会触发两次错误提示  后续更改为监听选中数组 选择事件 大于1 return
      if (sleect.length == 1) {
        this.sleect = sleect;
      } else {
        this.$message.error("只能选择一条数据");
        this.$refs.roleTable.$refs.multipleTable.clearSelection();
      }
    },
  },
  created() {
    if (this.formData) {
      this.searchOptions = this.formData;
    }
  },
};
</script>
